package com.ychen.springbatch.skip;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenyuliao
 * @version 1.0
 * @description
 * @date 2020/10/18 15:56
 */
@Configuration
public class SkipDemo {


    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    ItemProcessor<Customer, Customer> firstNameUpperProcessor;

    @Bean
    public Job skipDemoJob() {
        return jobBuilderFactory.get("skipDemoJob")
                .start(skipDemoStep())
                .build();
    }

    @Bean
    public Step skipDemoStep() {
        return stepBuilderFactory.get("skipDemoStep")
                .<Customer, Customer>chunk(1)
                .reader(read())
                .processor(firstNameUpperProcessor)
                .writer(write())
                .faultTolerant()
                .skip(CustomException.class)
                .skipLimit(5) // 最多跳过5次
                .build();
    }

    @Bean
    public ItemWriter<Customer> write() {
        return new ItemWriter<Customer>() {
            @Override
            public void write(List<? extends Customer> list) throws Exception {
                for (Customer item : list) {
                    System.out.println("item: " + item.toString());
                }
            }
        };
    }

    @Bean
    public ItemReader<Customer> read() {
        List<Customer> customerList = new ArrayList<>();
        Customer c1 = new Customer();
        c1.setId("1");
        c1.setFirstName("Jackson");
        c1.setLastName("Michael");
        c1.setBirthday("1958.08.29");
        customerList.add(c1);

        Customer c2 = new Customer();
        c2.setId("2");
        c2.setFirstName("Kobe");
        c2.setLastName("Bryant");
        c2.setBirthday("1978.08.23");
        customerList.add(c2);

        return new ListItemReader<>(customerList);
    }


}
